mui.init();
var readSectionDetails;
var ebookid;
mui.plusReady(function () {
    //返回全屏
	var old_back = mui.back;
	mui.back = function() {
	    plus.navigator.setFullscreen(false);
	    old_back();
	}
	//拦截侧滑返回事件
	var _self = plus.webview.currentWebview();
	_self.addEventListener("popGesture",function() {
	    plus.navigator.setFullscreen(false);
	});
    plus.navigator.setStatusBarStyle('dark');
    var self = plus.webview.currentWebview();
    ebookid = self.bookid;
    var sid = self.sid;
    var buyStatus = self.buyStatus;
    var flag = false;
    readSectionDetails = new Vue({
        el: '#content_details',
        data: {
            sid:sid ? sid : '',
            details: '',
            fs: 16,
            light: 0.25,
            he: 1.5,
            jd: 50,
            noteBookCon: '',
            yes_num: 300,
            color_index:0,

            topTitleBar:flag,
            bottomBar:flag,
            notesBox:flag,
            popMask:flag,
            fontBox:flag,
        },
        mounted() {
            this.getEbookSectionDetails();
        },
        computed: {
            prev: function () {
                if (this.details.prev_id == null) {
                    return -1;
                } else {
                    return this.details.prev_id;
                }
            },
            next: function () {
                if (this.details.next_id == null) {
                    return -1;
                } else {
                    return this.details.next_id;
                }
            },
            styleObject: function () {
                if (this.details.bookmark == 'YES') {
                    var color = {
                        color: '#FC3934'
                    };
                    return color;
                } else {
                    var color = {
                        color: '#8f8f94'
                    };
                    return color;
                }
            },
        },
        watch: {
            fs: function () {
                $('.read_box p ,.read_box p span').css('fontSize', this.fs + 'px');
            },
            light: function () {
                plus.screen.setBrightness(this.light);
            },
            he: function () {
                $('.read_box p').css('lineHeight', (this.he));
            },
            jd: function (val,oldVal) {
                var mh = $(".mui-content").height();
                mui('.mui-content').scroll().scrollTo(0,((val)/100)*mh,100);
            },
            noteBookCon: function () {
                var str = this.noteBookCon;
                var len = str.replace(/[\u0391-\uFFE5]/g, "aa").length;
                this.yes_num = 300 - len;
            },
            sid:function (val,oldVal) {
                this.getEbookSectionDetails(val);
            }
        },
        methods: {
            getEbookSectionDetails: function (sid = this.sid) {
                //获取阅读内容
                showWatting();
                console.log(sid);
                var api_host = plus.storage.getItem('HOST_URL');
                var self = this;
                mui.ajax({
                    url: api_host + '/api/ebook/index/read',
                    dataType: 'json',
                    headers:{'User-Token':plus.storage.getItem('UserToken')},
                    data: {
                        'bookid': ebookid,
                        'sid':sid ? sid : '',
                    },
                    type: 'get',
                    success: function (msg) {
                        if (msg.code == 1) {
                            self.details = '';
                            self.details = msg.data;
                            self.$nextTick(function () {
                                mui('.mui-scroll-wrapper').scroll({
                                    deceleration: 0.0006,
                                    scrollY: true,
                                    indicators: true,
                                    bounce: true,
                                    startX: 0,
                                    startY: 0,
                                }).scrollTo(0,0,100);
                            })
                        } else {
                            mui.toast(msg.msg, {duration: '200',type: 'div'});
                        }
                    },
                    error: function () {
                        mui.toast('加载失败，请重试', {duration: '200',type: 'div'});
                    },
                    complete:function (XMLHttpRequest,status) {
                        plus.nativeUI.closeWaiting();
                    }
                })
            },
            toTop: function() {
            	mui('.mui-scroll-wrapper').scroll({
                    deceleration: 0.002, //flick 减速系数，系数越大，滚动速度越慢，滚动距离越小，默认值0.0006
                    scrollY: true,
                    indicators: true,
                    bounce: true
                }).scrollTo(0,0,300);
            },
            backRead: function(){
            	plus.webview.currentWebview().close();
            },
            open_bottom_box: function () { //弹出底部BAR
                this.bottomBar = !this.bottomBar;
                this.topTitleBar = !this.topTitleBar;
                // this.notesBox = !this.notesBox;
                // this.fontBox = !this.fontBox;
                var onOff = true;
                //控制全屏显示隐藏
                if(this.bottomBar == true && this.topTitleBar == true){
                	plus.navigator.setFullscreen(false);
                }else{
                	plus.navigator.setFullscreen(true);
                }
                
            },
            open_mulu: function () { //打开目录
                mui.openWindow({
                    url: 'catalogTab.html',
                    extras: {
                        'bookid': ebookid,
                        'buy_status': buyStatus,
                        'bookTitle':this.details.section_title
                    },
                    createNew:false,
                    show: {
                        autoShow: true,
                        aniShow: 'pop-in',
                        duration: 400
                    },
                    waiting: {
                        autoShow: false,
                    }
                });
				this.bottomBar = !this.bottomBar;
                this.topTitleBar = !this.topTitleBar;
            },
            setBgColor:function(e,ind){
                this.color_index = ind;
                //设置背景颜色
                var arrBg = ['#F3F3F3', '#EAE3CF', '#E7F7E9', '#9CBDBF', '#010202'];
                var arrColor = ['#384049', '#384049', '#384049', '#384049', '#666'];
                $('body').css({
                    'backgroundColor': arrBg[ind-1],
                });
                if (ind == 4) {
                    $('.read_box p ,.read_box h3 ,.read_box h4').css({
                        'color':arrColor[4]
                    });
                }
            },
            set_font: function () { //设置字体
                var self = this;
                this.fontBox = !this.fontBox;
                $('.read_box').on('tap', function () {
                    self.fontBox = false;
                });
            },
            set_noetbook: function () { //添加笔记
                this.popMask = true;
                this.bottomBar = false;
                this.topTitleBar = false;
                this.notesBox = true;
            },
            set_shuqian: function () { //设置书签
                var self = this;
                var api_host = plus.storage.getItem('HOST_URL');
                mui.ajax({
                    url: api_host + '/api/ebook/index/set_shuqian',
                    dataType: 'json',
                    headers:{'User-Token':plus.storage.getItem('UserToken')},
                    timeout:3000,
                    data: {
                        'bookid': ebookid,
                        'section_id': self.details.id,
                        'section_title': self.details.section_title
                    },
                    type: 'POST',
                    success: function (msg) {
                        self.details.bookmark = msg.data.status;
                        mui.toast(msg.msg, {duration: '2000',type: 'div'});
                    },
                    error: function () {
                        mui.toast("书签设置失败请重试！", {duration: '2000',type: 'div'});
                    }
                })
            },
            notebook_submit: function () {
                //提交笔记
                var self = this;
                var len = self.noteBookCon.replace(/[\u0391-\uFFE5]/g, "aa").length;
                if (len == 0) {
                    mui.toast('笔记内容不能为空哦!', {duration: '2000',type: 'div'});
                    return false;
                } else if (len > 300) {
                    mui.toast('长度超过300个字符哦，请重新填写再提交!', {duration: '2000',type: 'div'});
                    return false;
                }                
                var api_host = plus.storage.getItem('HOST_URL');
                mui.ajax({
                    url: api_host + '/api/ebook/index/add_notebook',
                    dataType: 'json',
                    headers:{'User-Token':plus.storage.getItem('UserToken')},
                    timeout:3000,
                    data: {
                        'bookid': ebookid,
                        'section_id': self.details.id,
                        'content': self.noteBookCon,
                        'section_title': self.details.section_title
                    },
                    type: 'POST',
                    success: function (msg) {
                        mui.toast(msg.msg, {duration: '2000',type: 'div'});
                    },
                    error: function () {
                        mui.toast("添加笔记失败请重试！", {duration: '2000',type: 'div'});
                    },
                    complete:function () {
                        setTimeout(function () {
                            self.popMask = false;
                            self.bottomBar = false;
                            self.topTitleBar = false;
                            self.notesBox = false;
                            self.noteBookCon = '';
                        }, 800)
                    }
                })

            },
            close_notebook: function () {
                this.popMask = false;
                // this.bottomBar = false;
                this.topTitleBar = false;
                this.notesBox = false;
                this.fontBox = false;
            },
            prev_page: function (sid) {
                this.getEbookSectionDetails(sid);
            },
            next_page: function (sid) {
                this.getEbookSectionDetails(sid);
            },
        }
    })
});

var backButtonPress = 0;
mui.back = function(event) {
    backButtonPress++;
    if (backButtonPress > 1) {
        setTimeout(function(){
            updateEbookPostion();
            var obj = plus.webview.all();
            $.each(obj,function (index,value) {
                if(value.id == 'read.html'){
                    plus.webview.getWebviewById('read.html').close();
                }
            });
            // plus.webview.currentWebview().close();
            // console.log(JSON.stringify(plus.webview.all()));
            plus.screen.setBrightness(0.5);
            plus.navigator.setFullscreen(false);
            mui.back();
            
        }, 100)
    } else {
        plus.nativeUI.toast('再按一次退出阅读');
    }
    setTimeout(function() {
        backButtonPress = 0;
    }, 2000);
    return false;
};

//记录图书阅读进度
function updateEbookPostion() {
    var api_host = plus.storage.getItem('HOST_URL');
    /*console.log(ebookid);
    console.log(readSectionDetails.details.id);*/
    mui.ajax({
        url: api_host + '/api/ebook/index/update_ebook_postion',
        dataType: 'json',
        headers:{'User-Token':plus.storage.getItem('UserToken')},
        timeout:3000,
        data: {
            'bookid': ebookid,
            'read_section': readSectionDetails.details.id,
        },
        type: 'POST',
        success: function (msg) {
            mui.toast(msg.msg, {duration: '1000',type: 'div'});
        },
        error: function () {
            console.log('读书进度标记出错了');
        }
    })
}
